/**
 * title: 状态共享
 */

import { useRef } from 'react';
import { useEffect, useReducer } from 'react';

/**共享对象 */
const obj = {
  a: 1,
};
window.obj = obj;

/**reducer */
const reducer = (state = obj, action) => {
  if (action.type === 'add') {
    return { ...state, a: action.text };
  }
  return state;
};

/**自定义use */
function useTodos() {
  const [todos, dispatch] = useReducer(reducer, obj);

  const handleAddClick = text => {
    dispatch({ type: 'add', text });
  };

  return [todos, { handleAddClick }];
}

/**输出组件 */
function Todos() {
  const [todos, actions] = useTodos();

  // console.log(todos);

  const input = useRef('');

  const click = () => {
    actions.handleAddClick(input.current.value || 0);
  };

  return (
    <div>
      <h3>父组件</h3>
      <button onClick={click}>111</button>
      <input type="text" ref={input} />
      <div>{JSON.stringify({ a: String(todos.a) })}</div>
      <A1 todos={todos} />
    </div>
  );
}

/**子组件 */
function A1(props) {
  return (
    <div>
      <h3>子组件</h3>
      <div>{JSON.stringify({ a: String(props.todos.a) })}</div>
    </div>
  );
}

export default Todos;
